package com.itheima.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map<String, String> map, HttpServletRequest request) {
        try {
            //2. 从map中获取手机号和用户输入的验证码
            String telephone = map.get("telephone");
            String validateCode = map.get("validateCode");
            //3. 按照手机号和验证码类型从redis中获取发送过的验证码和用户输入的验证码进行比较
            String code = jedisPool.getResource().get(telephone + "-" + RedisMessageConstant.SENDTYPE_LOGIN);
            //4. 如果验证码不一致，则提示错误信息
            if (StringUtils.isEmpty(code)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            if (!StringUtils.isEquals(validateCode, code)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            //5. 验证码一致，判断是否是会员
            Member member = memberService.findByTel(telephone);
            //5.1 非会员则保存会员信息
            if (null == member) {
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            // 则登陆并且保存登陆信息（Session）
            HttpSession session = request.getSession();
            session.setAttribute("member",member);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }
    }
}
